import React, { useState } from "react";
import { Input, Tag } from "antd-mobile";
import { BaseInfo, ChatRoom, LoginUser } from "../../../serve/interfaces";
import { connect, getState } from "@/store";
import { chatroom_update } from '../../apis/apiNode'


export interface Props {
  chatroom: ChatRoom & BaseInfo;
  loginUser: LoginUser;
}

const ChatRoomName = (props: Props) => {
  const { chatroom, loginUser } = props
  const [editing, setEditing] = useState(false)

  if (!chatroom) {
    return <></>
  }
  const onEditing = () => {
    if (chatroom.is_controlled) {
      return
    }
    const self = chatroom.users.find(u => u.username === loginUser.username)
    if (!self) {
      return
    }
    if (self.is_admin || self.is_master) {
      setEditing(true)
    }
  }
  const onChange = (value: string) => {
    const _name = (value || '').trim()
    if (_name && _name != chatroom.name) {
      chatroom_update({
        _id: chatroom._id,
        name: _name,
      })
    } else {
      setEditing(false)
    }
  }
  return editing ? <Input
    placeholder={chatroom.name}
    defaultValue={chatroom.name}
    onBlur={e => onChange(e.target.value)}
  /> : <div onClick={onEditing}>
    {chatroom.name} &nbsp; {chatroom.is_deleted && <Tag style={{ verticalAlign: 1 }}>已解散</Tag>}
  </div>
}

export default connect(getState)(ChatRoomName)
